<?php
namespace core;


class Response {
    private int $statusCode = 0; //状态码
    private array $headers = []; //http 请求头
    private string $body; //返回数据


    public function addHeader($name, $value): void {
        $this->headers[$name] = $value;
    }

    public function text($body): void {
        $this->statusCode = 200;
        $this->body = $body;
    }

    public function json($val): void {
        $this->statusCode = 200;
        $this->body = json_encode($val);

        $this->addHeader('Content-Type', 'application/json');
    }

    public function abort($body = ''): void {
        $this->statusCode = 200;
        $this->body = $body;
    }

    public function abortWithCode(int $code, $body = ''): void {
        $this->statusCode = $code;
        $this->body = $body;
    }

    public function send(): void {
        if (!$this->statusCode) {
            $this->statusCode = 404;
            $this->body = '404 NOT FOUND';
        }

        http_response_code($this->statusCode);

        foreach ($this->headers as $name => $value) {
            header("$name: $value");
        }

        echo $this->body;
    }
}
